package com.android.djlmapp.activity.my;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.constraint.ConstraintLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.android.djlmapp.R;
import com.android.djlmapp.adapter.my.FBTypeAdapter;
import com.android.djlmapp.adapter.my.FeedBackAdapter;
import com.android.djlmapp.application.MyApplication;
import com.android.djlmapp.base.BaseActivity;
import com.android.djlmapp.model.my.FeedBackInfo;
import com.android.djlmapp.view.NoScrollGridView;
import com.android.djlmapp.view.NoScrollListView;
import com.android.readcard.utils.LogUtils;
import com.android.readcard.utils.ToastUtils;
import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class FeedBackActivity extends BaseActivity {
    private final String[] SXArr = new String[]{"充值问题", "开卡错误", "加款未到账", "身份证读取失败", "人脸识别失败", "订单问题", "App闪退", "电子钱包出错"};
    public static final String TAG = "djlm-my: ";

    @BindView(R.id.ll_top_back)
    LinearLayout llTopBack;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.home_iv_readpoint)
    ImageView homeIvReadpoint;
    @BindView(R.id.iv_top_msg)
    ConstraintLayout ivTopMsg;
    @BindView(R.id.iv_top_set)
    ImageView ivTopSet;
    @BindView(R.id.iv_top_kf)
    ImageView ivTopKf;
    @BindView(R.id.page_title_layout)
    ConstraintLayout pageTitleLayout;
    @BindView(R.id.fb_gridview)
    NoScrollGridView gridView;
    @BindView(R.id.fb_edit)
    EditText fbEdit;
    @BindView(R.id.fb_num)
    TextView fbEditNum;
    @BindView(R.id.fk_listview)
    NoScrollListView fkListview;
    @BindView(R.id.scrollView)
    ScrollView scrollView;
    @BindView(R.id.refresh)
    SwipeRefreshLayout swipeRefreshLayout;

    @BindView(R.id.null_data_layout)
    RelativeLayout mNullDataLayout;
    @BindView(R.id.connect_net_error_layout)
    LinearLayout mConnectNetErrorLayout;

    private Unbinder mUnbinder;
    private FeedBackAdapter mAdapter;
    private Context mContext;
    private String content;
    private String remark;
    ArrayList<FeedBackInfo.DataBean> beanList = new ArrayList<>();
    private int mPageSize = 1;
    private boolean isClear = false;
    private FBTypeAdapter adapter;
    private boolean isHadData = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feed_back);
        mUnbinder = ButterKnife.bind(this);
        mContext = getActivity();
        initView();

        initData();
    }

    @Override
    protected void initView() {
        llTopBack.setVisibility(View.VISIBLE);
        ivTopMsg.setVisibility(View.GONE);
        ivTopSet.setVisibility(View.GONE);
        ivTopKf.setVisibility(View.GONE);
        tvName.setText("意见反馈");

        shaixuan();

        fbEdit.addTextChangedListener(phoneTextW);  //监听输入框变化
        swipeRefreshLayout.setColorSchemeResources(R.color.homeBule);

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Log.i(TAG, "refsh");
                mPageSize = 1;
                isClear = true;
                isHadData = false;

                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        swipeRefreshLayout.setEnabled(false);
                        initData();
                    }
                });
            }
        });

        mAdapter = new FeedBackAdapter(this);
        fkListview.setAdapter(mAdapter);
    }

    @Override
    protected void initData() {
        MyApplication.getInstance().getHttpTools().feedBack(mPageSize, callback);
    }

    StringCallback callback = new StringCallback() {
        @Override
        public void onSuccess(Response<String> response) {
            LogUtils.e(TAG, "意见反馈: " + response.body());
            try {
                FeedBackInfo messageEntity = new Gson().fromJson(response.body(), FeedBackInfo.class);
                if (messageEntity != null) {
                    List<FeedBackInfo.DataBean> msgs = messageEntity.getData();
                    Log.i("意见反馈", "onSuccess: " + msgs.size());
                    if ("200".equals("" + messageEntity.getCode())) {
                        normalLayout();

                        if (msgs != null && msgs.size() > 0) {
                            if(isClear){
                                beanList = new ArrayList<>();
                                isClear = false;
                                isHadData = false;
                                mPageSize = 1;

                                beanList.addAll(msgs);
                                mAdapter.setData(beanList);
                                Log.i(TAG, "加载...........");

                            }else{
                                mAdapter.add(msgs);
                            }

                            if (msgs.size() >= 10) {
                                mPageSize++;
                                isHadData = true;
                            }else {
                                isHadData = false;
                            }
                        }else{
                            noDataLayout();
                        }

                        Log.i(TAG, "isHadData: " + isHadData);
                    } else if ("2001".equals("" + messageEntity.getCode()) && mPageSize > 1){
                        isHadData = false;
                    } else {
                        mAdapter.clear();
                        Log.i(TAG, "200 else");
                        String wanningMsg = messageEntity.getMsg();
                        showErrorLayout(false, wanningMsg);
                    }
                } else {
                    mAdapter.clear();
                    showErrorLayout(false, "服务端异常");
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                showToast("数据解析异常");
            }
        }

        @Override
        public void onError(Response<String> response) {
            showToast("网络或服务器错误");

        }

        @Override
        public void onFinish() {
            if (swipeRefreshLayout != null) {
                swipeRefreshLayout.setRefreshing(false);
                swipeRefreshLayout.setEnabled(true);
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mUnbinder.unbind();
    }


    @OnClick({R.id.ll_top_back, R.id.fb_sub})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_top_back:
                finish();
                break;
            case R.id.fb_sub:
                closeKB();
                postInfo();
                break;
        }
    }

    private void postInfo() {
        if (remark == null || TextUtils.isEmpty(remark)) {
            ToastUtils.showShortToastSafe(mContext, "请选择反馈类型");
        } else {
            content = fbEdit.getText().toString();
            if (TextUtils.isEmpty(content)) {
                ToastUtils.showShortToastSafe(mContext, "请输入反馈信息");
                return;
            }
            MyApplication.getInstance().getHttpTools().feedBackPost(content, remark, new StringCallback() {
                @Override
                public void onSuccess(Response<String> response) {
                    LogUtils.e(TAG, "意见反馈提交: " + response.body());

                    try {
                        JSONObject json = new JSONObject(response.body());

                        if("200".equals(json.getString("code"))){
                            fbEdit.setText("");
                            isClear = true;
                            mPageSize = 1;
                            swipeRefreshLayout.setRefreshing(true);
                            initData();
                        }
                        ToastUtils.showShortToastSafe(mContext, json.getString("msg"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                        ToastUtils.showShortToastSafe(mContext, "数据解析异常!");
                    }
                }

                @Override
                public void onError(Response<String> response) {
                    super.onError(response);
                    ToastUtils.showShortToastSafe(mContext, "网络或服务器错误!");

                }
            });
        }
    }

    private void shaixuan() {
        List list = Arrays.asList(SXArr);
        adapter = new FBTypeAdapter(this, list);
        gridView.setAdapter(adapter);

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                adapter.setSelectedIndex(position);
                adapter.notifyDataSetInvalidated();

                remark = SXArr[position];


            }
        });
    }

    /**
     * 监听输入框变化
     */
    TextWatcher phoneTextW = new TextWatcher() { // EditText变化监听

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.length() <= 200) {
                fbEditNum.setText(s.length() + "/200");
            } else {
                // 提示
                ToastUtils.showShortToast(FeedBackActivity.this, "字数超过限制");
            }
        }
    };

    /**
     * 显示布局
     * @param isNetError  是否是网络错误
     * @param warnningMsg 提示信息
     */
    private void showErrorLayout(boolean isNetError, String warnningMsg) {
        if (isHadData) {
            normalLayout();
            ToastUtils.showShortToastSafe(mContext, warnningMsg);
        } else {
            if (isNetError) {
                connectNetErrorLayout();
            } else {
                noDataLayout();
            }
        }
    }

    /**
     * 无数据状态
     */
    private void noDataLayout() {
        Log.i(TAG, "无数据状态");
        if (mNullDataLayout.getVisibility() == View.GONE) {
            mConnectNetErrorLayout.setVisibility(View.GONE);
            mNullDataLayout.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 网络错误状态
     */
    private void connectNetErrorLayout() {
        if (mConnectNetErrorLayout.getVisibility() == View.GONE) {
            mNullDataLayout.setVisibility(View.GONE);
            mConnectNetErrorLayout.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 正常布局状态
     */
    private void normalLayout() {
        if (mConnectNetErrorLayout.getVisibility() == View.VISIBLE || mNullDataLayout.getVisibility() == View.VISIBLE) {
            mConnectNetErrorLayout.setVisibility(View.GONE);
            mNullDataLayout.setVisibility(View.GONE);
        }
    }

    private void  closeKB() {
        //关闭键盘
        try {
            View view = getWindow().peekDecorView();
            if (view != null) {
                InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
        } catch (Exception e) {
        }
    }
}

